import pickle

def isPrime(number,List):
    if number<List[-1]:
        if number in List:
            return True
        else:
            return False
    else:
        flag=0
        while List[flag]**2<=number:
            if number%List[flag]==0:
                return False
            flag+=1
        return True

def p60num(pa,pb,Listp):
    pc=str(pa)+str(pb)
    if isPrime(int(pc),Listp)==False:
        return False
    pc=str(pb)+str(pa)
    if isPrime(int(pc),Listp)==False:
        return False
    return True
upper=20000
F=open('prime.txt','r')
prime=pickle.load(F)
F.close()

prime1=[]
for x in prime:
    if x%3==1:
        prime1.append(x)

F=open('primekid.txt','r')
prime=pickle.load(F)
F.close()

for p1 in prime1:
    if sum>0 and p1>sum:
        break
    if p1>upper:
        break
    for p2 in prime1:
        if sum>0 and p1+p2>sum:
            break
        if p2>upper:
            break
        if p2<=p1:
            continue
        if p60num(p1,p2,prime)==False:
            continue
        for p3 in prime1:
            if sum>0 and p1+p2+p3>sum:
                break
            if p3>upper:
                break
            if p3<=p2:
                continue
            if p60num(p1,p3,prime)==False or p60num(p2,p3,prime)==False:
                continue
            for p4 in prime1:
                if sum>0 and p1+p2+p3+p4>sum:
                    break
                if p4>upper:
                    break
                if p4<=p3:
                    continue
                if p60num(p1,p4,prime)==False or p60num(p2,p4,prime)==False or p60num(p3,p4,prime)==False:
                    continue
                for p5 in prime1:
                    if sum>0 and p1+p2+p3+p4+p5>sum:
                        break
                    if p5>upper:
                        break
                    if p5<=p4:
                        continue
            
                    if p60num(p1,p5,prime)==False or p60num(p2,p5,prime)==False or p60num(p3,p5,prime)==False or p60num(p4,p5,prime)==False:
                        continue
                    print 'p1=',p1,'p2=',p2,'p3=',p3,'p4=',p4,'p5=',p5,'sum=',p1+p2+p3+p4+p5
